package com.coocaa.ops.admin.base.interceptor;

import com.coocaa.ops.admin.base.annotation.Auth;
import com.coocaa.ops.admin.base.constant.SessionConstants;
import com.coocaa.ops.admin.base.util.WebUtil;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.common.tool.exception.LoginException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tangminghong
 * @date 2020-06-17
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            Auth authPassport = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
            String path = request.getServletPath();
            //没有声明需要权限,或者声明不验证权限
            if (authPassport == null || !authPassport.verifyLogin()) {
                return true;
            } else {
                if (WebUtil.isSwagger(request)){
                    return true;
                }
                //权限验证逻辑
                SysUserEntity user = getCurrentUserIfLoggedIn(request);
                if (user != null) {
                    //如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                    return true;
                } else {
                    //如果验证失败
                    boolean isOk = false;
                    if (!isOk) {
                        if (path != null && path.contains("/v1/")) {
                            //返回401状态码
                            response.setStatus(401);
                        } else {
                            //返回到登录界面
                            response.sendRedirect("/index.html");
                        }
                        return false;
                    }
                    return true;
                }
            }
        } else {
            return true;
        }
    }


    private SysUserEntity getCurrentUserIfLoggedIn(HttpServletRequest request) {
        SysUserEntity user;
        try {
            user = WebUtil.getCurrentUser(request);
        } catch (LoginException e) {
            user = null;
        }
        return user;
    }
}
